package com.jwater.core.net;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jwater.core.annotation.JwaterRpcService;

import jwater.org.springframework.core.io.Resource;
import jwater.org.springframework.core.type.AnnotationMetadata;
import jwater.org.springframework.core.type.classreading.MetadataReader;
import jwater.org.springframework.core.type.classreading.MetadataReaderFactory;
import jwater.org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
/**
 * @description:
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class RegisterRpcService {
	protected static Logger logger = LoggerFactory.getLogger(RegisterRpcService.class);

	private static Map<String, String> services = new HashMap<String, String>();
	private static ConcurrentHashMap<String, Object> serviceInstances = new ConcurrentHashMap<String, Object>();

	static {
		try {
			registerService();
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
	}

	/**
	 * 注册服务
	 * 
	 * @throws Exception
	 */
	protected static void registerService() throws Exception {
		List<Resource> resources = ScanRpcServiceConfig.getScanResource();
		MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
		for (Resource resource : resources) {
			if (resource.isReadable()) {
				MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
				AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
				if (metadata.isAnnotated(JwaterRpcService.class.getName())) {
					Map<String, Object> map = metadata.getAnnotationAttributes(JwaterRpcService.class.getName(), true);
					services.put((String) map.get("superClazz"), metadata.getClassName());
				}
			}
		}
	}

	/**
	 * 添加服务，覆盖式的
	 * 
	 * @param superClazz
	 * @param clazz
	 */
	public static void addService(Class<?> superClazz, Class<?> clazz) {
		services.put(superClazz.getName(), clazz.getName());
	}

	/**
	 * 移除服务
	 * 
	 * @param superClazz
	 */
	public static void removeService(Class<?> superClazz) {
		services.remove(superClazz.getName());
	}

	/**
	 * 根据父类获取实现类的名称
	 * 
	 * @param superClazz
	 * @return
	 */
	protected static String getServiceClazzName(String superClazz) {
		return services.get(superClazz);
	}

	/**
	 * 获取服务实例
	 * 
	 * @param clazzName
	 * @return
	 * @throws ClassNotFoundException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	protected static Object getServiceInstance(String clazzName)
			throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Object serviceInstance = serviceInstances.get(clazzName);
		if (serviceInstance == null) {
			Class<?> clazz = Class.forName(clazzName);
			serviceInstance = clazz.newInstance();
			serviceInstances.put(clazzName, serviceInstance);
		}
		return serviceInstance;
	}
}
